package com.bgs.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import com.bgs.pojo.User;
import com.bgs.service.LoginService;
import com.bgs.tool.GuliException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过

        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 执行认证
        if (StringUtils.isBlank(token)) {
                throw new GuliException(20001,"无token，请重新登录");
        }
        // 获取 token
        String email;
        try {
            email = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new GuliException(20001,"token验证失败，请重新登录");
        }

        User u=loginService.getEmail(email);
        // 验证 token
        JWTVerifier jwtVerifier = null;
        if (u.getPassword() == null) {

            throw new GuliException(20001,"用户不存在，请重新登录");
        }else{
            jwtVerifier = JWT.require(Algorithm.HMAC256(u.getPassword())).build();
        }

        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            //throw new GuliException(20001,"token验证失败，请重新登录");
        }
        return true;


    }
}
